package page111;

public class Rational {
    int numerator;
    int denominator;

    public int getNumerator() {
        return this.numerator;
    }

    public int getDenominator() {
        return this.denominator;
    }

    public void setNumeratorAndDenominator(int num, int den) {
        int temp = this.greatestCommonDivisor(num, den);
        if (den < 0) {
            num *= -1;
            den *= -1;
        }
        this.numerator = num / temp;
        this.denominator = den / temp;


    }

    public int greatestCommonDivisor(int num1, int num2) {
        num1 = Math.abs(num1);
        num2 = Math.abs(num2);
        int max = Math.max(num1, num2);
        int i, temp = 0;
        for (i = 1; i <= max; i++) {
            if (num1 % i == 0 && num2 % i == 0)
                temp = i;
        }
        return temp;
    }

    public Rational add(Rational r) {
        int n = r.getNumerator();
        int d = r.getDenominator();
        Rational result = new Rational();
        int resultD = this.denominator * d;
        int resultN = this.numerator * d + n * this.denominator;
        int temp = this.greatestCommonDivisor(resultN, resultD);
        result.setNumeratorAndDenominator(resultN / temp, resultD / temp);
        return result;
    }

    public Rational sub(Rational r) {
        int n = r.getNumerator();
        int d = r.getDenominator();
        Rational result = new Rational();
        int resultD = this.denominator * d;
        int resultN = this.numerator * d - n * this.denominator;
        int temp = this.greatestCommonDivisor(resultN, resultD);
        result.setNumeratorAndDenominator(resultN / temp, resultD / temp);
        return result;
    }

    public Rational muti(Rational r) {
        int n = r.getNumerator();
        int d = r.getDenominator();
        Rational result = new Rational();
        int resultD = this.denominator * d;
        int resultN = this.numerator * n;
        int temp = this.greatestCommonDivisor(resultN, resultD);
        result.setNumeratorAndDenominator(resultN / temp, resultD / temp);
        return result;
    }

    public Rational div(Rational r) {
        int n = r.getNumerator();
        int d = r.getDenominator();
        Rational result = new Rational();
        int resultD = this.denominator * n;
        int resultN = this.numerator * d;
        int temp = this.greatestCommonDivisor(resultN, resultD);
        result.setNumeratorAndDenominator(resultN / temp, resultD / temp);
        return result;
    }
}
